package c04.thread.safe;

import java.util.ArrayList;

/**
 * 从这个例子可以看出private与final可以为线程安全提供保障。
 */
public class ThreadSafeSubClass extends ThreadSafe {
    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 20;

    public static void main(String[] args) {
        ThreadSafeSubClass t = new ThreadSafeSubClass();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> {
                t.testAddRemove(LOOP_NUMBER);
            }, "Thread" + (i+1)).start();
        }
    }

    @Override
    public void remove(ArrayList<String> list) {
        // 局部变量list会被方法调用线程与下面新创建的线程共享，从而产生竞态条件
        new Thread(() -> {
            System.out.println(2);
            list.remove(0);
        }).start();
    }
}